package com.koron.device.utils;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.koron.common.core.util.FastJsonUtils;
import com.koron.device.bean.Select;
import com.koron.device.bean.TGParams;
import com.koron.device.bean.template.DynamicColumnVo;
import com.koron.device.bean.template.ExportExcelMsg;
import javassist.*;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.StringMemberValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class EqExportOrImpUtils {


    /**
     * 表格列头生成
     *
     * @param paramInfo
     */
    public static List<ExcelExportEntity> extracted(Map<String, String> paramInfo) {
        //表头的集合，用于添加表头
        List<ExcelExportEntity> entityList = new ArrayList<>();

        //ExcelExportEntity构造参数【第一个是列名头的统计字段,第二个是需要指定的一个key在填充数据的时候是需要根据这个key进行填充值,第三个参数是列宽】
//        ExcelExportEntity platformXh = new ExcelExportEntity("统计字段1", "statisKey1", 30);
//        //列的合并(纵向列的同名称会进行合并,效果见上图的平台名称的变化)
//        platformXh.setMergeVertical(true);
//        entityList.add(platformXh);
//
//        ExcelExportEntity statisDateXh = new ExcelExportEntity("统计字段2", "statisKey2", 30);
//        entityList.add(statisDateXh);

        //参数信息--[用于动态拼接列头]
        final Iterator<String> iterator = paramInfo.keySet().iterator();
        while (iterator.hasNext()) {
            final String paramKeyStr = iterator.next();
            final String paramNameStr = paramInfo.get(paramKeyStr);
            //列头由参数汉字名称,参数key为列key
            entityList.add(new ExcelExportEntity(paramNameStr, paramKeyStr, 30));
        }
        return entityList;
    }


    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 编写填写标准
     *
     * @param tgParams
     * @param hashMap
     */
    public static void editStandarMsg(List<TGParams> tgParams, Map<String, String> hashMap) {
        for (TGParams tgParam : tgParams) {
            if (StrUtil.equalsAny(tgParam.getEnterType(), "radio", "multi")) {
                List<Select> selectlist = FastJsonUtils.getJsonToList(tgParam.getDataText(), Select.class);
                // 单选、多选 之允许 label 范围内填写
                String standardMsg = selectlist.stream().map(Select::getLabel).collect(Collectors.joining("、"));
                hashMap.put(tgParam.getParamName(), StrUtil.format("请在以下范围参数范围内填写：{}", standardMsg));
                continue;
            }
            if (StrUtil.equals(tgParam.getDataType(), "date")) {
                // 日期格式参数
                hashMap.put(tgParam.getParamName(), StrUtil.format("请以yyyy-MM-dd的格式填写"));
                continue;
            }
            if (StrUtil.equals(tgParam.getDataType(), "text")) {
                // 日期格式参数
                hashMap.put(tgParam.getParamName(), StrUtil.format("文本长度不能大于:{}", tgParam.getDataLength()));
                continue;
            }
            if (StrUtil.equals(tgParam.getDataType(), "number")) {
                // 数字格式参数
                hashMap.put(tgParam.getParamName(), StrUtil.format("请填写数字"));
                continue;
            }
        }
        hashMap.put("安装位置完整路径", "请填写:完整位置路径,位置之间以 斜杆(/) 连接");
        hashMap.put("安装位置名称", "界面展示路径");
        for (String paramName : ExportExcelMsg.getInitExport()) {
            hashMap.put(paramName, "本列不允许修改");
        }
    }

    public static final String CLASS_NAME_PREFIX = "com.jtech.toa.utils.EasyPoiExcelVO@";
    public static final String ANNOTATION_PACKAGE_NAME = "cn.afterturn.easypoi.excel.annotation.Excel";
    public static final String STRING_PACKAGE_NAME = "java.lang.String";

    public static Class<?> generatePrototypeClass(List<DynamicColumnVo> list)
            throws NotFoundException, CannotCompileException, IOException {
        String className = CLASS_NAME_PREFIX + UUID.randomUUID().toString();
        ClassPool pool = ClassPool.getDefault();
        CtClass clazz = pool.makeClass(className);
        ClassFile ccFile = clazz.getClassFile();
        ConstPool constpool = ccFile.getConstPool();
        //添加fields
        addExpressField(pool, clazz, constpool, list);

        return clazz.toClass();
    }

    private static void addExpressField(ClassPool pool, CtClass clazz, ConstPool constpool, List<DynamicColumnVo> list) throws CannotCompileException, NotFoundException {
        for (DynamicColumnVo dynamicColumnDto : list) {
            addFieldAndAnnotation(pool, clazz, constpool, dynamicColumnDto.getTitle(), dynamicColumnDto.getField());
        }
    }


    private static void addFieldAndAnnotation(ClassPool pool, CtClass clazz, ConstPool constpool, String titleName, String fieldName) throws NotFoundException, CannotCompileException {
        //生成field
        CtField field = new CtField(pool.get(STRING_PACKAGE_NAME), fieldName, clazz);
        field.setModifiers(Modifier.PUBLIC);
        //添加easypoi的注解
        AnnotationsAttribute fieldAttr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        Annotation annotation = new Annotation(ANNOTATION_PACKAGE_NAME, constpool);
        annotation.addMemberValue("name", new StringMemberValue(titleName, constpool));
        fieldAttr.addAnnotation(annotation);
        field.getFieldInfo().addAttribute(fieldAttr);

        //生成get,set方法
        clazz.addMethod(CtNewMethod.getter("get" + upperFirstLatter(fieldName), field));
        clazz.addMethod(CtNewMethod.setter("set" + upperFirstLatter(fieldName), field));

        clazz.addField(field);
    }

    private static String upperFirstLatter(String letter) {
        return letter.substring(0, 1).toUpperCase() + letter.substring(1);
    }

    private static String getFieldValue(String fieldName, Object data) throws Exception {
        Method m = (Method) data.getClass().getMethod(
                "get" + EqExportOrImpUtils.upperFirstLatter(fieldName));
        return (String) m.invoke(data);
    }

    public static List<Map<String, String>> parseObjectList(List<?> result) throws Exception {
        List<Map<String, String>> parseResult = Lists.newArrayList();
        if (CollUtil.isNotEmpty(result)) {
            Class<?> clazz = result.get(0).getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Object data : result) {
                Map<String, String> parseDataMap = Maps.newConcurrentMap();
                for (Field field : fields) {
                    String value = getFieldValue(field.getName(), data);
                    parseDataMap.put(field.getName(), value == null ? "" : value);
                }
                parseResult.add(parseDataMap);
            }
        }
        return parseResult;
    }


    /**
     * 读取excel
     *
     * @param file   excel文件
     * @param Suffix 文件后缀名，判断是不是excel文件，区分excel版本
     * @return
     */
    public static Workbook readExcel(MultipartFile file, String Suffix) {
        Workbook wb = null;
        if (file == null) {
            return null;
        }
        InputStream is = null;
        try {
            is = file.getInputStream();
            if ("xls".equals(Suffix)) {
                return wb = new HSSFWorkbook(is);
            } else if ("xlsx".equals(Suffix)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return wb;
    }


    /**
     * 获取excel第一个sheet的第一行数据
     *
     * @param file
     * @param fileName
     * @return
     */
    public static LinkedHashSet<String> getTopRow(MultipartFile file, String fileName, int rowNum) {
        List<String> split1 = StrUtil.split(fileName, ".");
        String suffix = CollUtil.get(split1, -1);
        LinkedHashSet<String> result = new LinkedHashSet<>();
        Workbook wb = readExcel(file, suffix); //文件
        Sheet sheet = wb.getSheetAt(0); //sheet
        Row row = sheet.getRow(rowNum);
        for (int i = 0; i < row.getLastCellNum(); i++) {
            String cellData = (String) getCellFormatValue(row.getCell(i));
            result.add(cellData.replaceAll(" ", ""));
        }
        return result;

    }

    private static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判断cell类型
            CellType cellType = cell.getCellType();
            switch (cellType) {
                case NUMERIC: {
                    if (DateUtil.isCellDateFormatted(cell)) {
                        //excel文件内的日期列若设置单元格格式为日期，读取的值和文件内看到的不一样，
                        //需要根据num对应的格式进行转换，最好是直接在上传页面强制要求单元格格式为文本一劳永逸，
                        //因为num对应的日期格式不同版本的jar包不一样，成本太高但是工期够就无所谓了可慢慢研究。
                        short num = cell.getCellStyle().getDataFormat();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        cellValue = df.format(cell.getDateCellValue());
                    } else {
                        cell.setCellType(CellType.STRING);  //将数值型cell设置为string型
                        cellValue = cell.getStringCellValue();
                    }
                    break;
                }
                case FORMULA: {
                    //判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        //数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}
